<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of owlpost
 *
 * @author trung
 */
class Owl_Page extends Owl_Db{

    function Owl_Page(){
        $this->Owl_Db('page');
    }

    function get_all_pages(){
        return $this->get_results('//page');
    }

    function get_pages_for_rss() {
        return array_slice(array_reverse((array)$this->get_results('//page')), 0, get_option("content_per_page", 10));
    }

    function get_page($nice_url) {
        if ( empty($nice_url) )
            return false;
        return $this->get_row('/pages/page[nice_url="'.$nice_url.'"]');
    }

    function get_last_page_url($type) {
        $last_page = end($this->get_all_pages());
        if ($last_page) {
            if ($type == 'view')
                return Owl_Link::page_url($last_page["nice_url"], false);
            else
                return Owl_Link::template_url('edit-page', false, array('var' => $last_page["nice_url"]));
        }
        else {
            return false;
        }
    }

    function get_pages_menu() {
        $pages = $this->get_all_pages();
        if ($pages) {
            $pages = array_reverse($pages);
            $max_pages_display = get_option('max_pages_display', 5);
            $data = array();
            for ($i = 0; $i < min($max_pages_display, count($pages)); $i++) {
                $data[$pages[$i]["nice_url"]] = $pages[$i]["title"];
            }
            return $data;
        }
        else {
            return false;
        }
    }

    function insert_pages($data){
        if ($this->get_page($data["nice_url"])) {
            $this->last_error = new Owl_Error('506', __('Page title is duplicated'));
            return false;
        }
        $now = Owl_Date_Time::current_time('xml');
        $file = Owl_Date_Time::current_time('timestamp').".owl";
        $defaults = array(
                            'title' => '',
                            'create_date' => $now,
                            'modify_date' => $now,
                            'excerpt' => '',
                            'image_thumb' => '',
                            'nice_url' => Owl_Format::remove_accents($data['title']),
                            'content_file' => $file
                        );
        $data = Owl_System_Helper::array_merge($data, $defaults);
        return $this->insert('/pages', 'page', $data);
    }

    function delete_pages($nice_url){
        if ( empty($nice_url) )
            return false;
        return $this->delete('/pages/page[nice_url="'.$nice_url.'"]');
    }

    function update_pages($nice_url, $data){
        if ( empty($nice_url) )
            return false;
        $old_page = $this->get_page($nice_url);
        if ($old_page === false){
            $this->last_error = new Owl_Error('506', __('Page does not exist'));
            return false;
        }
        $now = Owl_Date_Time::current_time('xml');
        $defaults = array(
                            'title' => $old_page['title'],
                            'create_date' => $old_page["create_date"],
                            'modify_date' => $now,
                            'excerpt' => $old_page['excerpt'],
                            'image_thumb' => $old_page['image_thumb'],
                            'nice_url' => $old_page['nice_url'],
                            'content_file' => $old_page['content_file']
                        );
                        
        $data = Owl_System_Helper::array_merge($data, $defaults);
        $data = Owl_Format::esc_html_deep($data);
        
        return $this->update('/pages/page[nice_url="'.$nice_url.'"]','page', $data);
    }

    function to_json($args = array()) {
        $page = 1;
        extract($args);

        $data = array();
        $pages = $this->get_all_pages();
        if ($pages === false) {
            $data["code"] = 0;
            $data["message"] = $this->get_error();
        }
        else {
            $pages = array_reverse($pages);

            //Paging
            $total = count($pages);
            $page_boundary = Owl_Functions::get_pagination_boundary($page, $total);

            if ($page_boundary !== false) {
                $data["code"] = 1;
                $data["message"] = "Success";
                $data["total"] = ceil($total / get_option("content_per_page", 15));

                list($begin, $end) = $page_boundary;
                $data["hasTab"] = false;
                $data["hasHeader"] = true;
                $data["rows"] = array();

                //Fetch content
                for ($i = $begin; $i <= $end; $i++) {
                    $aPage = $pages[$i];
                    $row = array();
                    $row["header"] = '<span>' . Owl_Format::esc_html($aPage["title"]) . '</span>';
                    
                    $row["content"][] = '<div class="page-thumbnail"><a href="' . Owl_Link::page_url($aPage["nice_url"], false) . '">' . Owl_Html::make_it_image(Owl_Link::site_url(false) . $aPage["image_thumb"], Owl_Format::esc_html($aPage["title"]), 96) .  '</a></div>';
                    $row["content"][] = '<div class="page-excerpt">' . Owl_Format::esc_html($aPage["excerpt"]) . '</div>';
                    if ($aPage["create_date"] == $aPage["modify_date"]) {
                        $row["content"][] = "<div class=\"page-detail\">" . sprintf(__('Posted by <span class="page-author">%s</span> at <span class="page-time">%s</span>'), Owl_Default_Content::get_site_author(), Owl_Date_Time::w3c_to_owl_date($aPage["create_date"])) . "</div>";
                    }
                    else {
                        $row["content"][] = "<div class=\"page-detail\">" . sprintf(__('Modified by <span class="page-author">%s</span> at <span class="page-time">%s</span>'), Owl_Default_Content::get_site_author(), Owl_Date_Time::w3c_to_owl_date($aPage["modify_date"])) . "</div>";
                    }
                    $row["content"][] = '<div class="pages-detail-link"><a href="' . Owl_Link::page_url($aPage["nice_url"], false) . '">' . __("View detail") . '</a></div>';
                    
                    $data["rows"][] = $row;
                }
            }
            else {
                $data["code"] = 0;
                $data["message"] = __("No data");
            }
            $data["controlText"] = Owl_Functions::get_control_text();
            return Owl_Functions::json_encode($data);
        }
    }

    function print_form($data = array()) {
?>
<form action="<?php Owl_Link::ajax_url() ?>pages-ajax.php" method="POST" id="<?php echo (empty($data)) ? "add-page" : "edit-page" ?>" enctype="multipart/form-data">
    <?php
    Owl_Form::print_hidden(array(
        "name" => "action",
        "value" => (empty($data)) ? "add_page" : "edit_page"
    ));
    if (!empty($data)) {
        Owl_Form::print_hidden(array(
            "name" => "nice_url",
            "value" => $data["nice_url"]
        ));
    }
    ?>
    <div id="basic-container">
        <div id="title-container">
            <h3><?php echo __("Title"); ?></h3>
            <?php
            Owl_Form::print_textbox(array(
                "name" => "page_title",
                "class" => "form-textbox " . Owl_Functions::build_validate_string(array("required")),
                "value" => Owl_Format::esc_html($data["title"])
            ));
            ?>
        </div>
        <div id="content-container">
            <h3><?php echo __("Content"); ?></h3>
            <div style="width:95%; margin:auto;">
            <?php
            if (!empty($data)) {
                $content = htmlspecialchars(@file_get_contents(PAGE_PATH . $data["content_file"]));
            }
            else {
                $content = "";
            }
            Owl_Form::print_textarea(array(
                "name" => "page_content",
                "rows" => 10,
                "id" => "page_content",
                "class" => "ckeditor",
                "value" => $content
            ));
            ?>
            </div>
        </div>
    </div>
    <h3 id="advance-toggle"><?php echo __("Advance"); ?></h3>
    <div id="advance-container">        
        <h4><?php echo __("Excerpt"); ?></h4>
        <div id="excerpt-container">
            <?php
            Owl_Form::print_textarea(array(
                'name' => 'page_excerpt',
                'value' => Owl_Format::esc_html($data["excerpt"]),
                'rows' => 5,
                'description' => __("This is your page summary. The excerpt will be display in the pages list. You can leave this field empty, OWL will automatically summazire the content for you.")
            ));
            ?>
        </div>
        <h4><?php echo __("Thumbnail"); ?></h4>
        <div id="thumbnail-container">
            <?php
            Owl_Form::print_file_image(array(
                "name" => "page_image_thumb",
                "value" => empty($data["image_thumb"]) ? "" : Owl_Link::site_url(false) . $data["image_thumb"],
                "width" => 96,
                'description' => __("This is the thumbnail of your page. This image will be display in the pages list beside your excerpt. The image size should be 96px width.")
            ));
            if (!empty($data)) {
                Owl_Form::print_label(array(
                    "value" => __("Use default thumbnail"),
                    "for" => "use_default_thumb"
                ));
                Owl_Form::print_check_box(array(
                    "name" => "use_default_thumb",
                    "id" => "use_default_thumb"
                ));
            }
            ?>
        </div>
        <div style="clear:both; float:none;"></div>
    </div>
    <div id="button-container">
        <?php Owl_Default_Content::print_ajax_feedback(false); ?>
        <div class="form-button-pane">
            <?php
            Owl_Form::print_button(array(
                "name" => "submit_form",
                "value" => __("Save and view"),
                "class" => "form-button page-ajax-submit-view"
            ));
            if (empty($data)) {
                Owl_Form::print_button(array(
                    "name" => "submit_form",
                    "value" => __("Save and edit"),
                    "class" => "form-button page-ajax-submit-edit"
                ));
            }
            Owl_Form::print_button(array(
                "type" => "reset",
                "name" => "cancel",
                "value" => __("Cancel"),
                "class" => "form-button cancel-submit"
            ));
            ?>
        </div>
    </div>
</form>
<?php
    }

    function print_pages_pagination_dropdown() {
        $all_pages = $this->get_all_pages();
        $max_content_display = get_option("content_per_page", 10);
        if (count($all_pages) <= $max_content_display) {
            echo "&nbsp;";
            return false;
        }
        echo '<span style="margin-right:10px;">' . __("Pages") .  '</span>';
        $total_pages = ceil(count($all_pages) / $max_content_display);
        for ($i = 1; $i <= $total_pages; $i++) {
            $options[$i] = $i;
        }
        Owl_Form::print_combo_box(array(
            "name" => "pages_pagination",
            "id" => "pages_pagination_dropdown",
            "options" => $options
        ));
    }

    function print_pages_table($page) {
        $all_pages = $this->get_all_pages();
        if ($all_pages == false) {
?>
            <tr>
                <td colspan="3">
                    <?php echo __("No data"); ?>
                </td>
            </tr>
<?php
        }
        else {
            $all_pages = array_reverse($all_pages);
            $total = count($all_pages);
            $pagination = Owl_Functions::get_pagination_boundary($page, $total);
            if ($pagination == false) {
?>
                <tr>
                    <td colspan="3">
                        <?php echo __("No data"); ?>
                    </td>
                </tr>
<?php
            }
            else {
                list ($begin, $end) = $pagination;
                for ($i = $begin; $i <= $end; $i++) {
?>
                <tr>
                    <td>
                        <div><a href="<?php Owl_Link::page_url($all_pages[$i]["nice_url"]) ?>" title="<?php echo $all_pages[$i]["title"]; ?>"><?php echo Owl_Format::trim_text($all_pages[$i]["title"], 40); ?></a></div>
                        <div class="page-control" style="display:none;">
                            <a href="<?php Owl_Link::template_url('edit-page', true, array("var" => $all_pages[$i]["nice_url"])); ?>" class="info-extra edit"><span><?php echo __("Edit") ?></span></a>
                            <a href="#" rel="<?php echo $all_pages[$i]["nice_url"]; ?>" class="page-delete info-extra delete"><span><?php echo __("Delete") ?></span></a>
                        </div>
                    </td>
                    <td>
                        <?php echo Owl_Date_Time::w3c_to_owl_date($all_pages[$i]["create_date"], 'short'); ?>
                    </td>
                    <td>
                        <?php echo Owl_Date_Time::w3c_to_owl_date($all_pages[$i]["modify_date"], 'short'); ?>
                    </td>
                </tr>
<?php
                }
            }
        }
    }
    
    function to_rss() {
        $rss_data = $this->get_pages_for_rss();
        echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        echo '<rss version="2.0">' . "\n";
        echo '<channel>' . "\n";
        echo '<title>' . Owl_Format::esc_html(get_option('site_name')) . ' - ' . __("Pages") . '</title>' . "\n";
        echo '<link><![CDATA[' . "http://" . $_SERVER["HTTP_HOST"] . Owl_Link::template_url("pages", false) . ']]></link>' . "\n";
        echo '<description>' . sprintf(__("Pages from %s"), Owl_Format::esc_html(get_option('site_name'))) . '</description>' . "\n";
        if (!empty ($rss_data)) {
            foreach ($rss_data as $item) {
                echo '<item>'."\n";
                echo '<title><![CDATA[' . Owl_Format::esc_html($item["title"]) .']]></title>'."\n";
                echo '<link><![CDATA[' . "http://" . $_SERVER["HTTP_HOST"] . Owl_Link::page_url($item["nice_url"], false) . ']]></link>'."\n";
                echo '<description><![CDATA[' . Owl_Format::esc_html($item["excerpt"]) . ']]></description>'."\n";
                echo '<pubDate><![CDATA[' . Owl_Date_Time::w3c_to_date($item["create_date"], DATE_RSS, false, false) . ']]></pubDate>'."\n";
                echo '</item>'."\n";
            }
        }
        echo '</channel>' . "\n";
        echo '</rss>';
    }
}

